/*
 * Copyright (c) 2021 Zsj. All rights reserved.
 */

package com.jzz.crawlerweb.handler.generator.impl;

import com.jzz.crawlerweb.handler.generator.ImageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.util.Random;

public class DrawTextImageHandler implements ImageHandler {
    private static final Logger logger = LoggerFactory.getLogger(DrawTextImageHandler.class);
    private final Color[] colors = new Color[]{
            Color.red, Color.blue, Color.pink, Color.magenta, Color.green
    };

    @Override
    public BufferedImage handle(BufferedImage bi, Object... args) {
        bi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
        int height = bi.getHeight();
        int width = bi.getWidth();
        try {
            String text = args[0].toString();
            int fontSize = Integer.parseInt(args[1].toString());
            int charSpace = Integer.parseInt(args[2].toString());
            Font[] fonts = new Font[]{
                    new Font("Arial", Font.BOLD, fontSize), new Font("Courier", Font.BOLD, fontSize)
            };

            Graphics2D g2d = (Graphics2D) bi.getGraphics();

            Random random = new Random();

            FontRenderContext frc = g2d.getFontRenderContext();

            int startPosY = (height - fontSize) / 5 + fontSize;

            char[] wordChars = text.toCharArray();
            Font[] chosenFonts = new Font[wordChars.length];
            int[] charWidths = new int[wordChars.length];
            int widthNeeded = 0;
            for (int i = 0; i < wordChars.length; i++) {
                chosenFonts[i] = fonts[random.nextInt(fonts.length)];

                char[] charToDraw = new char[]{
                        wordChars[i]
                };
                GlyphVector gv = chosenFonts[i].createGlyphVector(frc, charToDraw);
                charWidths[i] = (int) gv.getVisualBounds().getWidth();
                if (i > 0) {
                    widthNeeded = widthNeeded + 2;
                }
                widthNeeded = widthNeeded + charWidths[i];
            }

            int startPosX = (width - widthNeeded) / 2;
            for (int i = 0; i < wordChars.length; i++) {
                g2d.setFont(chosenFonts[i]);
                char[] charToDraw = new char[]{
                        wordChars[i]
                };

                g2d.setColor(colors[random.nextInt(colors.length)]);
                g2d.drawChars(charToDraw, 0, charToDraw.length, startPosX, startPosY);
                startPosX = startPosX + charWidths[i] + charSpace;
            }
        } catch (Exception e) {
            logger.error("Error occurs while handling image: ", e);
        }
        return bi;
    }
}
